package jwt

import (
	"context"
	"fmt"

	"server_1.0/api/internal/svc"
	"server_1.0/api/internal/types"
	"server_1.0/service/student/student"
	"server_1.0/util"

	"github.com/zeromicro/go-zero/core/logx"
)

type ChangePasswordLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewChangePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangePasswordLogic {
	return &ChangePasswordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ChangePasswordLogic) ChangePassword(req *types.StuChangePwdReq) (resp *types.PostReps, err error) {
	if req.NewPwd != req.NewPwdAgain {
		return nil, util.NewCodeError(util.ParamError, "两次输入密码不一致")
	}
	if req.NewPwd == req.OldPwd {
		return nil, util.NewCodeError(util.ParamError, "新旧密码不能一致")
	}
	code := util.Success
	Msg := "成功"
	nowID := fmt.Sprintf("%v", l.ctx.Value("userId"))
	Reps, err := l.svcCtx.StudentRpc.QueryID(l.ctx, &student.QueryIDReq{
		No: nowID,
	})
	if err != nil {
		code = util.NoFoundError
		Msg = "无记录"
	} else {
		sig := Reps.QRs[0]
		_, err := l.svcCtx.StudentRpc.Update(l.ctx, &student.UpdateReq{
			ID:       sig.ID[:8],
			No:       sig.ID[8:],
			Password: req.NewPwd,
			Sex:      sig.Sex,
			Name:     sig.Name,
			Age:      sig.Age,
		})
		if err != nil {
			code = util.AddError
			Msg = "修改失败"
		}
		return &types.PostReps{
			Code: code,
			Msg:  Msg,
			Data: map[string]interface{}{
				"No":           sig.ID,
				"New Password": req.NewPwd,
			},
		}, nil
	}
	return &types.PostReps{
		Code: code,
		Msg:  Msg,
	}, nil
}
